package org.irri.smta.ui.bean;

import java.io.Serializable;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.inject.Inject;
import javax.inject.Named;

import org.irri.smta.common.Constants;
import org.irri.smta.domain.User;
import org.irri.smta.global.GlobalBean;
import org.irri.smta.service.IUserService;
import org.irri.smta.util.BeanUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Named("loginBean")
@ViewScoped
public class LoginBean implements Serializable {

	private static final long serialVersionUID = 1L;
	private static final Logger LOGGER = LoggerFactory
			.getLogger(LoginBean.class);

	@Inject
	@Named("globalBean")
	private GlobalBean globalBean;

	@Inject
	@Named("themeSwitcherBean")
	private ThemeSwitcherBean themeSwitcherBean;

	@Inject
	@Named("userService")
	private IUserService<User, Long> userService;

	private String username = "";
	private String password = "";
	private BeanUtils beanUtils = new BeanUtils();

	/**
	 * Constructor.
	 */
	public LoginBean() {
		super();
	}

	@PostConstruct
	public void init() {
		LOGGER.debug("Initialize " + LoginBean.class.getName());
		beanUtils.clearSessionUser();
		themeSwitcherBean.setDefaultTheme();
	}

	@PreDestroy
	private void destroy() {
		LOGGER.debug("Cleanup " + LoginBean.class.getName());
		beanUtils.clearSessionUser();
		username = "";
		password = "";
	}

	public void preRenderView() {
		LOGGER.debug("preRenderView()");
		beanUtils.clearSessionUser();
		themeSwitcherBean.setDefaultTheme();
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public void login() {
		LOGGER.debug("login()");
		FacesContext context = FacesContext.getCurrentInstance();

		if (username == null || username.trim().length() == 0
				|| password == null || password.trim().length() == 0) {
			defaultLogin();
			context.addMessage(null, new FacesMessage("Login Message",
					"Logging in as guest user."));
			beanUtils.navigateToView(Constants.SMTA_REPORT_HOME_VIEW_NAME);
		} else {
			List<User> userList = userService.findByUsernameAndPassword(
					username, password);
			if (userList != null && userList.size() == 1) {
				User user = userList.get(0);
				switchThemeForUser(user);
				beanUtils.setSessionUser(user);
				beanUtils.navigateToView(Constants.SMTA_REPORT_HOME_VIEW_NAME);
			} else {
				context.addMessage(null, new FacesMessage("Login Message",
						"Invalid username or password!"));
			}
		}
	}
	
	public void defaultLogin() {
		User user = userService.findById(Constants.DEFAULT_USER_ID);
		switchThemeForUser(user);
		beanUtils.setSessionUser(user);
	}

	private void switchThemeForUser(User user) {
		LOGGER.debug("switchThemeForUser(User user): " + user.getUsername());
		if (globalBean.canCreate(user) && globalBean.canUpdate(user)
				&& globalBean.canDelete(user)) {
			themeSwitcherBean.setAdministratorTheme();
		} else if (globalBean.canCreate(user) && globalBean.canUpdate(user)) {
			themeSwitcherBean.setDataEntryTheme();
		} else {
			themeSwitcherBean.setUserTheme();
		}
	}

	@Override
	public String toString() {
		return "LoginBean [username=" + username + "]";
	}

}
